package com.accounting.client.session;

import com.allen_sauer.gwt.log.client.Log;

import corelib.client.jsonrpc.exception.IncompatibleJSONRemoteServiceException;
import corelib.client.jsonrpc.exception.UnexpectedJSONMessageException;
import corelib.client.jsonrpc.impl.platform.ErrorCode;
import corelib.client.jsonrpc.impl.platform.ServiceError;
import corelib.client.jsonrpc.impl.platform.ServiceErrorParser;
import corelib.client.ui.widget.messagebox.SimpleMessageBox;

public class ErrorHandler {
	
	public static void handleServiceError(Throwable caught) {
		ServiceError serviceError = convertToServiceError(caught);
		SimpleMessageBox.error("Error", caught.getMessage(), null);
		/*if (serviceError.getCode() == ErrorCode.ServerInternal) {
			Log.info("Service Error:" + serviceError, caught);
			SimpleMessageBox.error("Internal Server Error", "Server is not available.", null);
			return;
		}
		
		if (serviceError.getCode() == ErrorCode.InvalidRequest) {
			Log.info("Invalid request: " + serviceError, caught);
			SimpleMessageBox.error("Invalid Request", serviceError.getMessage(), null);
			return;
		}

		if (serviceError.getCode() == ErrorCode.Unauthorised) {
			Log.info("Unauthorised: " + serviceError, caught);
			SimpleMessageBox.error("Unauthorised", serviceError.getMessage(), null);
			return;
		}
		
		if (serviceError.getCode() == ErrorCode.MultipleLogin) {
			Log.info("Multiple login: " + serviceError, caught);
			SimpleMessageBox.error("Unauthorised", serviceError.getMessage(), null);
			SessionManager.logout();
			return;
		}

		if (serviceError.getCode() == ErrorCode.Unauthenticated) {
			SimpleMessageBox.error("Unauthenticated", serviceError.getMessage(), null);
			SessionManager.logout();
			return;
		}
*/
		Log.error("Unexpected Error: " + serviceError, caught);
	}
	
	public static ServiceError convertToServiceError(Throwable error) {
		Log.debug("error : " + error.getMessage());
		if (error instanceof IncompatibleJSONRemoteServiceException) {
			IncompatibleJSONRemoteServiceException incompatible = (IncompatibleJSONRemoteServiceException) error;
			return new ServiceError(ErrorCode.ServerInternal, incompatible.getMessage(), incompatible.getText());
		}
		if (error instanceof UnexpectedJSONMessageException) {
			UnexpectedJSONMessageException invalid = (UnexpectedJSONMessageException) error;
			ServiceError serviceError = ServiceErrorParser.parseJsonException(invalid.getText());
			if (serviceError != null) {
				return serviceError;
			}
			return new ServiceError(ErrorCode.InvalidRequest, invalid.getMessage(), invalid.getText());
		}
		return new ServiceError(ErrorCode.Unexpected, error.getMessage());
	}

}
